package cn.tedu.ximart.server.service.impl;

import cn.tedu.ximart.server.ex.ServiceException;
import cn.tedu.ximart.server.mapper.AttributeMapper;
import cn.tedu.ximart.server.pojo.dto.AttributeAddNewDTO;
import cn.tedu.ximart.server.pojo.entity.Attribute;
import cn.tedu.ximart.server.pojo.vo.AttributeListItemVO;
import cn.tedu.ximart.server.repo.IAttributeRepository;
import cn.tedu.ximart.server.service.IAttributeService;
import cn.tedu.ximart.server.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class AttributeServiceImpl implements IAttributeService {

    @Autowired
    public IAttributeRepository attributeRepository;

    @Autowired
    private AttributeMapper attributeMapper;

    public AttributeServiceImpl(){
        System.out.println("AttributeServiceImpl的构造方法被调用了");
    }

    @Override
    public void addNew(AttributeAddNewDTO attributeAddNewDTO){
        String name = attributeAddNewDTO.getName();
        int count = attributeMapper.countByName(name);
        if(count>0){
            String message = "增加品牌失败，品牌名称【"+name+"】已经被占用";
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }
        Attribute attribute = new Attribute();
        BeanUtils.copyProperties(attributeAddNewDTO,attribute);
        int rows = attributeMapper.insert(attribute);
        if(rows!=1){
            String message = "添加分类失败，服务器繁忙，请稍后再尝试";
            log.error(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }
    }

    @Override
    public void deleteById(Long id) {
        int rows = attributeMapper.deleteById(id);
        if(rows != 1){
            String message = "删除分类失败，找不到id为"+id+"的数据";
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
    }

    @Override
    public List<AttributeListItemVO> getAttributes() {
        return null;
    }


}
